#include "stm8s.h"


#define CCR1_Val  ((uint16_t)0)
#define CCR2_Val  ((uint16_t)0)



void TIM1_Config(void)
{

	TIM1_DeInit();
	TIM1_Cmd(DISABLE);
	CLK_PeripheralClockConfig(CLK_PERIPHERAL_TIMER1,ENABLE);


/*
   TIM1_Period = 4000
   TIM1_Prescaler = 0
   TIM1_CounterMode = TIM1_COUNTERMODE_UP
   TIM1_RepetitionCounter = 0
   */
   TIM1_TimeBaseInit(0, TIM1_COUNTERMODE_UP, 4000, 0);//16MHz/4000=4000

	/* Channel 1 and 2 Configuration in PWM mode */
	/*
   TIM1_OCMode = TIM1_OCMODE_PWM2
   TIM1_OutputState = TIM1_OUTPUTSTATE_ENABLE
   TIM1_OutputNState = TIM1_OUTPUTNSTATE_ENABLE
   TIM1_Pulse = CCR1_Val
   TIM1_OCPolarity = TIM1_OCPOLARITY_LOW
   TIM1_OCNPolarity = TIM1_OCNPOLARITY_HIGH
   TIM1_OCIdleState = TIM1_OCIDLESTATE_SET
   TIM1_OCNIdleState = TIM1_OCIDLESTATE_RESET
   */
	TIM1_OC1Init(TIM1_OCMODE_PWM2, TIM1_OUTPUTSTATE_ENABLE, TIM1_OUTPUTNSTATE_ENABLE,
                CCR1_Val, TIM1_OCPOLARITY_LOW, TIM1_OCNPOLARITY_HIGH, TIM1_OCIDLESTATE_SET,
                TIM1_OCNIDLESTATE_RESET); 

   /*TIM1_Pulse = CCR2_Val*/
   TIM1_OC2Init(TIM1_OCMODE_PWM2, TIM1_OUTPUTSTATE_ENABLE, TIM1_OUTPUTNSTATE_ENABLE, CCR2_Val,
                TIM1_OCPOLARITY_LOW, TIM1_OCNPOLARITY_HIGH, TIM1_OCIDLESTATE_SET, 
                TIM1_OCNIDLESTATE_RESET);

	TIM1_OC1PreloadConfig(ENABLE);
	TIM1_OC2PreloadConfig(ENABLE);
	TIM1_CCxCmd(TIM1_CHANNEL_1, ENABLE);
	TIM1_CCxCmd(TIM1_CHANNEL_2, ENABLE);

	/* TIM1 Main Output Enable */
	TIM1_CtrlPWMOutputs(ENABLE);
	TIM1_Cmd(ENABLE);

	TIM1_SetCompare1(2000);
	TIM1_SetCompare2(2000);


}



//---------------------------------------------------------------------
#define __ENABLE_TIM1_CH1_CH2__ /* 使用一次后，就可以注释掉！！ */
 
#ifdef __ENABLE_TIM1_CH1_CH2__
#include "TIM4.h"
#define TIM1_OptionAddr (0x4803)        //OPT2 BIT1
 
void Check_TIM1_CH1CH2_OptionByte(void)
{
  uint16_t TIM1_Option_status;/*记录激活备选功能Beep/TIM2_CH1的状态*/
  TIM1_Option_status = FLASH_ReadOptionByte(TIM1_OptionAddr);
  /* ARF0 BIT: 1 enable TIM1 CH1 CH2 */
  if((TIM1_Option_status&0x0100) == 0x00)
  {
    FLASH_Unlock(FLASH_MEMTYPE_DATA);
    FLASH_ProgramOptionByte(TIM1_OptionAddr, (uint8_t)(0x01));
    FLASH_Lock(FLASH_MEMTYPE_DATA);
    /*使能TIM1 CH1 CH2 PWM */
    // delay10ms();
	for (u16 i = 0; i < 0xFF00; i++)
		IWDG_ReloadCounter();
	
    // WWDG_SWReset();
  }
}
#endif
